package com.macro.mall.portal.service.impl;

import com.macro.mall.portal.domain.Product;
import com.macro.mall.portal.service.ProductRepository;
import com.macro.mall.portal.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author：尚志豪
 * @Package：com.macro.mall.portal.service.impl
 * @Project：mall-swarm-B
 * @name：ProductServiceImpl
 * @Date：2024/11/1 17:26
 */
@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
    private ProductRepository productRepository;

    @Override
    public void preheatProducts(List<Long> productIds) {
        List<Product> products = productRepository.findAllById(productIds);
        for (Product product : products) {
            product.setPreheatStatus(1);
            productRepository.save(product);
        }
    }

    @Override
    public List<Product> getPreheatedProducts() {
        return productRepository.findByPreheatStatus(1);
    }

    @Override
    public boolean checkStock(Long productId) {
        Product product = productRepository.findById(productId).orElse(null);
        return product != null && product.getStock() > 0;
    }

    @Override
    public void deductStock(Long productId) {
        Product product = productRepository.findById(productId).orElseThrow(() -> new RuntimeException("商品不存在"));
        product.setStock(product.getStock() - 1);
        productRepository.save(product);
    }
}
